package com.cloudfast.common.decode;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudfast.common.Constant;

/**
 * 加密算法 数据库解密(yml/环境加密),密码密码,登入加密
 *
 * @author liuyw
 * @date 2020年9月25日
 */
public class DecodeUtils {

    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    private static final String SHA1 = "SHA-1";

    /**
     * yml 文件解密算法
     *
     * @param value
     * @return
     * @author liuyw
     */
    @SuppressWarnings("static-access")
    public static String decodeEnvironment(String value) {
        if (value.startsWith(Constant.ASE_ENVIRONMENT_PREFIX) && value.endsWith(Constant.ASE_ENVIRONMENT_SUFFIX)) {
            String encryptStr = value.replace(Constant.ASE_ENVIRONMENT_PREFIX, "")
                    .replace(Constant.ASE_ENVIRONMENT_SUFFIX, "");
            try {
                if (StringUtils.isNotEmpty(encryptStr)) {
                    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                    byte[] IV = Constant.ASE_IV.getBytes("UTF-8");
                    IvParameterSpec iv = new IvParameterSpec(IV);
                    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Constant.ASE_KEY.getBytes(), "AES"), iv);
                    byte[] decryptBytes = cipher.doFinal((new Base64()).decodeBase64(encryptStr.getBytes()));
                    value = new String(decryptBytes);
                }
            } catch (Exception e) {
                logger.error(e.getMessage());

            }
        }
        return value;
    }

    /**
     * 密码对比
     *
     * @param rawPassword
     * @param encodedPassword
     * @return
     */
    public static boolean matches(String rawPassword, String encodedPassword) {
        byte[] salt = DecodeUtils.decodeHex(encodedPassword.substring(0, 16));
        byte[] hashPassword = DecodeUtils.sha1(rawPassword.getBytes(), salt, 1024);
        return encodedPassword.equals(DecodeUtils.encodeHex(salt) + DecodeUtils.encodeHex(hashPassword));
    }

    /**
     * Hex编码.
     */
    private static String encodeHex(byte[] input) {
        return Hex.encodeHexString(input);
    }

    /**
     * Hex解码.
     */
    private static byte[] decodeHex(String input) {
        try {
            return Hex.decodeHex(input.toCharArray());
        } catch (DecoderException e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    private static byte[] sha1(byte[] input, byte[] salt, int iterations) {
        return digest(input, SHA1, salt, iterations);
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            if (salt != null) {
                digest.update(salt);
            }
            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            logger.error(e.getMessage());
        }
        return null;
    }

}
